{% extends 'base.html' %}
{% load static %}

{% block title %}{{ activity.title }} - Meet活动聚{% endblock %}

{% block extra_css %}
<style>
    .card-body{
        text-align: left;
    }
/* 相关活动样式 */
    .related-activity-item {
        transition: all 0.3s ease;
    }

    .related-activity-item:hover {
        background-color: #f8f9fa;
        border-radius: 8px;
        margin-left: -8px;
        margin-right: -8px;
        padding-left: 8px;
        padding-right: 8px;
    }

    .related-activity-item a:hover {
        color: #0d6efd !important;
    }

    .related-activities-list {
        max-height: 400px;
        overflow-y: auto;
    }

    /* 自定义滚动条 */
    .related-activities-list::-webkit-scrollbar {
        width: 4px;
    }

    .related-activities-list::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 10px;
    }

    .related-activities-list::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 10px;
    }

    .related-activities-list::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
    }

    .comment-item {
        transition: all 0.3s ease;
        position: relative; /* 为删除按钮定位做准备 */
        padding-top: 15px; /* 为删除按钮留出空间 */
    }

    .comment-item:hover {
        background-color: #f8f9fa;
    }

    .comment-reply {
        position: relative; /* 回复也需要相对定位 */
        padding-top: 15px;
    }

    /* 修复删除按钮样式 */
    .btn-delete-comment {
        opacity: 0.7;
        transition: opacity 0.3s ease;
        position: absolute;
        top: 10px;
        right: 10px;
        width: 30px; /* 固定宽度 */
        height: 30px; /* 固定高度 */
        display: flex; /* 使用flex布局 */
        align-items: center; /* 垂直居中 */
        justify-content: center; /* 水平居中 */
        padding: 0; /* 移除内边距 */
        z-index: 10; /* 确保在最上层 */
    }

    .btn-delete-comment:hover {
        opacity: 1;
        transform: scale(1.1); /* 悬停时稍微放大 */
    }

    .reply-form {
        border-left: 3px solid #28a745;
        padding-left: 15px;
    }

    #map-container {
        height: 400px;
        width: 100%;
        border-radius: 8px;
    }

    .btn.processing {
        opacity: 0.6;
        pointer-events: none;
    }

    .activity-cover-image {
        width: 100%;
        height: 400px;
        object-fit: cover;
    }

    /* 修复评论区标题间距 */
    .card-header h5 {
        margin-bottom: 0;
        padding-bottom: 8px;
    }

    /* 图片上传区域样式 - 完全重写解决重叠问题 */
    .image-upload-area {
        border: 2px dashed #dee2e6;
        border-radius: 8px;
        padding: 20px;
        background-color: #f8f9fa;
        transition: all 0.3s ease;
        margin: 20px 0;
    }

    .image-upload-area:hover {
        border-color: #007bff;
        background-color: #e9f7fe;
    }

    /* 图片上传标题区域 - 完全重写布局 */
    .image-upload-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #dee2e6;
    }

    .image-upload-title .form-label {
        margin: 0;
        font-weight: 600;
        color: #495057;
        font-size: 1rem;
    }

    .image-upload-title .badge {
        font-size: 0.75rem;
        white-space: nowrap;
    }

    .image-preview-container {
        min-height: 80px;
        margin: 15px 0;
    }

    .image-preview-item {
        position: relative;
        margin-bottom: 10px;
    }

    .image-preview-item img {
        transition: transform 0.3s ease;
        border-radius: 6px;
    }

    .image-preview-item:hover img {
        transform: scale(1.05);
    }

    .btn-remove-preview {
        position: absolute;
        top: 5px;
        right: 5px;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0;
        font-size: 12px;
        background: rgba(220, 53, 69, 0.9);
        border: none;
        color: white;
        z-index: 10;
    }

    /* 按钮组间距 */
    .image-upload-buttons {
        display: flex;
        gap: 10px;
        margin-top: 15px;
    }

    /* 修复评论图片显示 */
    .comment-image-preview {
        transition: all 0.3s ease;
        border-radius: 6px;
        width: 100%;
        height: 150px; /* 固定高度 */
        object-fit: cover; /* 保持比例裁剪 */
    }

    .image-wrapper {
        position: relative;
        cursor: pointer;
        border-radius: 8px;
        overflow: hidden;
        display: block;
        margin-bottom: 10px;
    }

    .image-wrapper:hover .comment-image-preview {
        transform: scale(1.05);
        filter: brightness(0.8);
    }

    .image-overlay {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        opacity: 0;
        transition: opacity 0.3s ease;
        pointer-events: none;
        z-index: 2;
    }

    .image-wrapper:hover .image-overlay {
        opacity: 1;
    }

    /* 图片模态框样式 */
    .image-modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.9);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s ease;
    }

    .image-modal.active {
        opacity: 1;
        visibility: visible;
    }

    .image-modal-content {
        max-width: 90%;
        max-height: 90%;
        position: relative;
        transform: scale(0.7);
        transition: transform 0.3s ease;
    }

    .image-modal.active .image-modal-content {
        transform: scale(1);
    }

    .image-modal img {
        max-width: 100%;
        max-height: 90vh;
        border-radius: 8px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
    }

    .image-modal-close {
        position: absolute;
        top: -40px;
        right: 0;
        background: rgba(255, 255, 255, 0.2);
        border: none;
        color: white;
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: background 0.3s ease;
    }

    .image-modal-close:hover {
        background: rgba(255, 255, 255, 0.3);
    }

    /* 调试样式 - 确保按钮可见 */
    .btn-select-images {
        border: 2px solid #007bff !important;
        background-color: #007bff !important;
        color: white !important;
        font-weight: bold !important;
    }

    /* Toast 提示样式 */
    .custom-toast {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 250px;
    }

    /* 点赞按钮样式 */
    .btn-like-comment.processing {
        opacity: 0.6;
        pointer-events: none;
    }

    .btn-like-comment:disabled {
        cursor: not-allowed;
    }

    /* 确保点赞按钮状态明确 */
    .btn-like-comment.btn-danger {
        background-color: #dc3545;
        border-color: #dc3545;
        color: white;
    }

    .btn-like-comment.btn-outline-danger {
        background-color: transparent;
        border-color: #dc3545;
        color: #dc3545;
    }

    .btn-like-comment.btn-outline-danger:hover {
        background-color: #dc3545;
        color: white;
    }

    /* 修复评论内容对齐 */
    .comment-content {
        text-align: left !important;
        line-height: 1.5;
        margin-right: 40px; /* 为删除按钮留出空间 */
    }

    .comment-content p {
        margin-bottom: 0.5rem;
        word-wrap: break-word;
    }

    /* 确保评论表单有足够间距 */
    #comment-form {
        margin-bottom: 2rem !important;
    }

    /* 修复评论区整体布局 */
    .comments-section {
        margin-top: 2rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="row">
        <!-- 活动主要信息 -->
        <div class="col-lg-8">
            <div class="card mb-4">
                <!-- 封面图片显示 - 添加安全处理 -->
                {% if activity.cover_image %}
                    <img src="{{ activity.get_cover_image_url }}"
                         class="card-img-top activity-cover-image"
                         alt="{{ activity.title }}"
                         onerror="this.onerror=null; this.src='{% static 'imgs/default-activity-cover.jpeg' %}'">
                {% else %}
                    <div class="card-img-top activity-cover-image bg-light d-flex align-items-center justify-content-center">
                        <div class="text-center text-muted">
                            <i class="bi bi-image" style="font-size: 3rem;"></i>
                            <p class="mt-2">暂无封面图片</p>
                        </div>
                    </div>
                {% endif %}

                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-3">
                        <h3>{{ activity.title }}</h3>
                        <span class="badge {% if activity.status == 'approved' %}bg-success{% else %}bg-warning{% endif %} badge-status">
                            {{ activity.get_status_display }}
                        </span>
                    </div>

                    <div class="mb-3">
                        {% if activity.category %}
                        <span class="badge bg-info">{{ activity.category.name }}</span>
                        {% endif %}
                        <span class="text-muted">
                            <i class="bi bi-eye"></i> {{ activity.view_count }} 浏览
                        </span>
                    </div>

                    <div class="mb-4">
                        <h5>活动详情</h5>
                        <p>{{ activity.description|linebreaks }}</p>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <p><i class="bi bi-calendar"></i> <strong>开始时间：</strong>{{ activity.start_time|date:"Y-m-d H:i" }}</p>
                            <p><i class="bi bi-calendar-check"></i> <strong>结束时间：</strong>{{ activity.end_time|date:"Y-m-d H:i" }}</p>
                        </div>
                        <div class="col-md-6">
                            <p><i class="bi bi-geo-alt"></i> <strong>活动地点：</strong>{{ activity.location }}</p>
                            <p><i class="bi bi-people"></i> <strong>参与人数：</strong>{{ activity.current_participants }}/{{ activity.max_participants }}</p>
                            <p>
                                <i class="bi bi-info-circle"></i> <strong>活动状态：</strong>
                                {% if activity.can_check_in %}
                                    <span class="badge bg-success">已开始</span>
                                {% else %}
                                    <span class="badge bg-warning">未开始</span>
                                    <small class="text-muted">（{{ activity.start_time|timeuntil }}后开始）</small>
                                {% endif %}
                            </p>
                        </div>
                    </div>

                    <!-- 地图 -->
                    {% if activity.latitude and activity.longitude %}
                    <div class="mb-4">
                        <h5>活动位置</h5>
                        <div id="map-container"></div>
                    </div>
                    {% endif %}

                    <!-- 操作按钮 -->
                    <div class="d-flex gap-2 mb-4">
                        {% if user.is_authenticated %}
                            {% if is_creator %}
                                <a href="{% url 'activities:activity_edit' activity.id %}" class="btn btn-warning">
                                    <i class="bi bi-pencil"></i> 编辑活动
                                </a>
                                <a href="{% url 'activities:activity_participants' activity.id %}" class="btn btn-info">
                                    <i class="bi bi-people"></i> 参与者列表
                                </a>
                            {% elif is_registered %}
                                <!-- 取消报名按钮 - 活动开始前显示 -->
                                {% if activity.can_cancel_registration %}
                                    <button class="btn btn-secondary btn-unregister-activity" data-activity-id="{{ activity.id }}">
                                        <i class="bi bi-x-circle"></i> 取消报名
                                    </button>
                                {% else %}
                                    <button class="btn btn-secondary" disabled title="活动已开始，无法取消报名">
                                        <i class="bi bi-x-circle"></i> 无法取消
                                    </button>
                                {% endif %}

                                <!-- 签到按钮 - 根据活动开始状态显示 -->
                                {% if is_checked_in %}
                                    <button class="btn btn-success" disabled>
                                        <i class="bi bi-check-circle"></i> 已签到
                                    </button>
                                {% else %}
                                    {% if activity.can_check_in %}
                                        <button class="btn btn-success btn-checkin" data-activity-id="{{ activity.id }}">
                                            <i class="bi bi-check-circle"></i> 签到
                                        </button>
                                    {% else %}
                                        <button class="btn btn-success" disabled title="活动开始后才可以签到">
                                            <i class="bi bi-check-circle"></i> 签到
                                        </button>
                                    {% endif %}
                                {% endif %}
                            {% elif activity.can_register %}
                                <button class="btn btn-primary btn-register-activity" data-activity-id="{{ activity.id }}">
                                    <i class="bi bi-person-plus"></i> 报名参加
                                </button>
                            {% else %}
                                <button class="btn btn-secondary" disabled>
                                    <i class="bi bi-x-circle"></i> 无法报名
                                </button>
                            {% endif %}
                        {% else %}
                            <a href="{% url 'users:login' %}?next={{ request.path }}" class="btn btn-primary">
                                <i class="bi bi-box-arrow-in-right"></i> 登录后报名
                            </a>
                        {% endif %}
                    </div>

                    <!-- 评分 -->
                    <div class="mb-4">
                        <h5>活动评分</h5>
                        <div class="rating-stars mb-2">
                            平均评分：<span class="average-rating">{{ average_rating }}</span>
                            {% for i in "12345" %}
                                <i class="bi bi-star{% if forloop.counter <= average_rating %}-fill{% endif %}"></i>
                            {% endfor %}
                        </div>
                        {% if user.is_authenticated %}
                        <div>
                            <p>您的评分：</p>
                            <div class="rating-stars">
                                {% if is_registered %}
                                    <!-- 已报名用户可以看到可点击的评分星星 -->
                                    {% for i in "12345" %}
                                    <i class="bi bi-star{% if user_rating and forloop.counter <= user_rating.score %}-fill{% endif %} rating-star"
                                       data-score="{{ forloop.counter }}"
                                       data-activity-id="{{ activity.id }}"
                                       style="cursor: pointer; font-size: 1.5rem; color: {% if user_rating and forloop.counter <= user_rating.score %}#ffc107{% else %}#6c757d{% endif %};"></i>
                                    {% endfor %}
                                    {% if not user_rating %}
                                    <small class="text-muted d-block mt-1">点击星星进行评分</small>
                                    {% endif %}
                                {% else %}
                                    <!-- 未报名用户看到禁用的评分星星 -->
                                    {% for i in "12345" %}
                                    <i class="bi bi-star{% if user_rating and forloop.counter <= user_rating.score %}-fill{% endif %}"
                                       style="font-size: 1.5rem; color: #dee2e6; cursor: not-allowed;"
                                       title="只有报名参加活动的用户才能评分"></i>
                                    {% endfor %}
                                    <small class="text-muted d-block mt-1">报名参加活动后即可评分</small>
                                {% endif %}
                            </div>
                        </div>
                        {% else %}
                        <div class="text-muted">
                            <i class="bi bi-star"></i>
                            <a href="{% url 'users:login' %}?next={{ request.path }}">登录</a> 后即可评分
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- 评论区 -->
            <div class="card comments-section">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="bi bi-chat-dots"></i> 评论区</h5>
                        <button class="btn btn-sm btn-outline-primary" id="manual-refresh-comments" title="刷新评论">
                            <i class="bi bi-arrow-clockwise"></i> 刷新
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    {% if user.is_authenticated %}
                    <!-- 发表评论表单 -->
                    <form id="comment-form" data-activity-id="{{ activity.id }}" class="mb-4" enctype="multipart/form-data">
                        {% csrf_token %}
                        <div class="mb-3">
                            <textarea class="form-control" name="content" rows="3" placeholder="发表您的评论..."></textarea>
                        </div>

                        <!-- 图片上传区域 - 完全重写的结构 -->
                        <div class="image-upload-area">
                            <div class="image-upload-title">
                                <label class="form-label">

                                </label>
                                <span class="badge bg-info">最多4张</span>
                            </div>

                            <!-- 隐藏的文件输入 -->
                            <input type="file" class="form-control comment-image-input"
                                   name="images" multiple accept="image/*" style="display: none;"
                                   id="main-image-input">

                            <!-- 图片预览区域 -->
                            <div class="image-preview-container row g-3" id="image-preview-main"></div>

                            <!-- 选择图片按钮 -->
                            <div class="image-upload-buttons">
                                <button type="button" class="btn btn-primary btn-sm btn-select-images"
                                        data-target="main" id="main-select-btn">
                                    <i class="bi bi-folder2-open"></i> 选择图片
                                </button>
                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearImagePreviews('main')">
                                    <i class="bi bi-trash"></i> 清空
                                </button>
                            </div>

                            <div class="mt-3">
                                <small class="form-text text-muted">
                                    <i class="bi bi-info-circle"></i> 支持 JPG、PNG 格式，每张图片不超过 5MB
                                </small>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-primary mt-3">
                            <i class="bi bi-send"></i> 发表评论
                        </button>
                    </form>
                    {% else %}
                    <p class="text-muted">
                        <a href="{% url 'users:login' %}?next={{ request.path }}">登录</a> 后发表评论
                    </p>
                    {% endif %}

                    <!-- 评论列表 - 使用部分模板 -->
                    <div class="comments-list">
                        {% include 'activities/partials/comments_list.html' %}
                    </div>
                </div>
            </div>
        </div>

        <!-- 侧边栏 -->
        <div class="col-lg-4">
            <!-- 发起人信息 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h6><i class="bi bi-person"></i> 活动发起人</h6>
                </div>
                <div class="card-body text-center">
                    <a href="{% url 'users:user_profile' activity.creator.id %}" class="text-decoration-none">
                        {% if activity.creator.avatar and activity.creator.avatar.url %}
                            <img src="{{ activity.creator.get_avatar_url }}"
                                 class="user-avatar-large mb-3"
                                 alt="{{ activity.creator.username }}"
                                 style="width: 150px; height: 150px; object-fit: cover; border-radius: 50%;"
                                 onerror="handleAvatarError(this)">
                        {% else %}
                            <!-- 统一的默认头像显示 -->
                            <img src='{% static 'imgs/default-avatar.jpg' %}'
                                 class="user-avatar-large mb-3"
                                 alt="{{ activity.creator.username }}"
                                 style="width: 150px; height: 150px; object-fit: cover; border-radius: 50%;">
                        {% endif %}

                        <h5 class="mt-2">{{ activity.creator.nickname|default:activity.creator.username }}</h5>
                    </a>
                    {% if activity.creator.signature %}
                    <p class="text-muted">{{ activity.creator.signature }}</p>
                    {% endif %}

                    <div class="d-flex gap-2 justify-content-center">
                        <a href="{% url 'users:user_profile' activity.creator.id %}" class="btn btn-sm btn-outline-primary">
                            查看主页
                        </a>
                        {% if user.is_authenticated and user != activity.creator %}
                            <button class="btn btn-sm {% if is_following %}btn-secondary{% else %}btn-outline-secondary{% endif %} btn-follow-user"
                                    data-user-id="{{ activity.creator.id }}">
                                <i class="bi {% if is_following %}bi-check{% else %}bi-plus{% endif %}"></i>
                                {% if is_following %}已关注{% else %}关注{% endif %}
                            </button>
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- 相关活动 -->
            <div class="card">
                <div class="card-header">
                    <h6><i class="bi bi-list"></i> 相关活动</h6>
                </div>
                <div class="card-body">
                    {% if related_activities %}
                        <div class="related-activities-list">
                            {% for related_activity in related_activities %}
                            <div class="related-activity-item mb-3 pb-3 {% if not forloop.last %}border-bottom{% endif %}">
                                <div class="d-flex align-items-start">
                                    <!-- 活动封面图片 -->
                                    <div class="flex-shrink-0 me-3">
                                        <a href="{% url 'activities:activity_detail' related_activity.id %}">
                                            {% if related_activity.cover_image %}
                                                <img src="{{ related_activity.get_cover_image_url }}"
                                                     class="rounded"
                                                     alt="{{ related_activity.title }}"
                                                     style="width: 80px; height: 60px; object-fit: cover;"
                                                     onerror="this.onerror=null; this.src='{% static 'imgs/default-activity-cover.jpeg' %}'">
                                            {% else %}
                                                <div class="bg-light rounded d-flex align-items-center justify-content-center"
                                                     style="width: 80px; height: 60px;">
                                                    <i class="bi bi-image text-muted"></i>
                                                </div>
                                            {% endif %}
                                        </a>
                                    </div>

                                    <!-- 活动信息 -->
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1">
                                            <a href="{% url 'activities:activity_detail' related_activity.id %}"
                                               class="text-decoration-none text-dark">
                                                {{ related_activity.title|truncatechars:20 }}
                                            </a>
                                        </h6>

                                        <div class="small text-muted mb-1">
                                            <i class="bi bi-calendar-event"></i>
                                            {{ related_activity.start_time|date:"m-d H:i" }}
                                        </div>

                                        <div class="small text-muted mb-1">
                                            <i class="bi bi-geo-alt"></i>
                                            {{ related_activity.location|truncatechars:15 }}
                                        </div>

                                        <div class="d-flex justify-content-between align-items-center">
                                            <span class="badge bg-info bg-opacity-10 text-info border border-info border-opacity-25">
                                                {{ related_activity.current_participants }}/{{ related_activity.max_participants }}
                                            </span>
                                            <small class="text-muted">
                                                <i class="bi bi-eye"></i> {{ related_activity.view_count }}
                                            </small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                    {% else %}
                        <div class="text-center py-3">
                            <i class="bi bi-inbox display-4 text-muted"></i>
                            <p class="text-muted mt-2 mb-0">暂无相关活动</p>
                            <small class="text-muted">看看其他分类的活动吧</small>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 图片预览模态框 -->
<div class="image-modal" id="imageModal">
    <div class="image-modal-content">
        <img id="modalImage" src="" alt="放大图片">
        <button class="image-modal-close">
            <i class="bi bi-x-lg"></i>
        </button>
    </div>
</div>

<!-- Toast 提示容器 -->
<div id="toastContainer" class="custom-toast"></div>
{% endblock %}

{% block extra_js %}
    <script>
    // 修复谷歌浏览器中汉堡菜单点击问题
document.addEventListener('DOMContentLoaded', function() {
    // 获取所有汉堡菜单按钮
    const hamburgerButtons = document.querySelectorAll('.rd-navbar-project-hamburger');

    // 为每个按钮添加点击事件监听器（确保使用捕获阶段）
    hamburgerButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.stopPropagation();
            e.preventDefault();

            // 手动触发切换效果
            const navbarMain = document.querySelector('.rd-navbar-main');
            navbarMain.classList.toggle('active');

            // 处理背景模糊效果
            const navbarWrap = document.querySelector('.rd-navbar-wrap');
            navbarWrap.classList.toggle('blur');
        }, true); // 使用捕获阶段
    });

    // 修复触摸设备兼容性
    hamburgerButtons.forEach(button => {
        button.addEventListener('touchstart', function(e) {
            e.stopPropagation();
            // 触发点击事件
            this.click();
        }, true);
    });
});
    </script>
<!-- 百度地图API -->
{% if activity.latitude and activity.longitude %}
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=ZZOx4JZUqi6j5ppMMjYmLoXe2Zs7Gb5X"></script>
<script>
    // 初始化百度地图
    var map = new BMap.Map("map-container");
    var point = new BMap.Point({{ activity.longitude }}, {{ activity.latitude }});
    map.centerAndZoom(point, 15);
    map.enableScrollWheelZoom(true);
    var marker = new BMap.Marker(point);
    map.addOverlay(marker);
    var infoWindow = new BMap.InfoWindow("{{ activity.location }}");
    marker.addEventListener("click", function() {
        this.openInfoWindow(infoWindow);
    });
    marker.openInfoWindow(infoWindow);
</script>
{% endif %}

<script>
// 全局状态管理
var commentState = {
    isSubmitting: false
};

var commentRefresh = {
    intervalId: null,
    isRefreshing: false
};

// Toast 提示函数
function showToast(message, type = 'info') {
    var toastHtml = `
        <div class="alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show" role="alert">
            <div class="d-flex align-items-center">
                <i class="bi ${type === 'error' ? 'bi-exclamation-triangle' : type === 'success' ? 'bi-check-circle' : 'bi-info-circle'} me-2"></i>
                <span>${message}</span>
                <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
            </div>
        </div>
    `;

    $('#toastContainer').html(toastHtml);

    // 3秒后自动消失
    setTimeout(function() {
        $('.alert').alert('close');
    }, 3000);
}

// 图片上传功能
function clearImagePreviews(target) {
    var $previewContainer = target === 'main' ?
        $('#image-preview-main') :
        $('#image-preview-' + target);
    $previewContainer.empty();

    // 清空文件输入
    if (target === 'main') {
        $('#main-image-input').val('');
    } else {
        $('#reply-form-' + target + ' .comment-image-input').val('');
    }
}

// 简化的图片上传功能初始化
function initImageUpload() {
    console.log('初始化图片上传功能...');

    // 选择图片按钮点击事件
    $(document).on('click', '.btn-select-images', function(e) {
        e.preventDefault();
        var target = $(this).data('target');
        console.log('点击选择图片按钮，目标:', target);

        var $fileInput = target === 'main' ?
            $('#main-image-input') :
            $('#reply-form-' + target + ' .comment-image-input');

        if ($fileInput.length === 0) {
            console.error('找不到文件输入框，目标:', target);
            return;
        }

        $fileInput.click();
    });

    // 文件选择变化事件
    $(document).on('change', '.comment-image-input', function(e) {
        var files = e.target.files;
        var target = $(this).attr('id') === 'main-image-input' ? 'main' :
                    $(this).closest('.reply-form').attr('id').replace('reply-form-', '');

        console.log('选择了', files.length, '个文件，目标:', target);

        var $previewContainer = target === 'main' ?
            $('#image-preview-main') :
            $('#image-preview-' + target);

        handleImageSelection(files, $previewContainer);
    });

    // 删除预览图片
    $(document).on('click', '.btn-remove-preview', function() {
        var previewId = $(this).data('preview-id');
        $('#' + previewId).remove();
        console.log('删除预览图片:', previewId);
    });

    console.log('图片上传功能初始化完成');
}

// 处理图片选择
function handleImageSelection(files, $previewContainer) {
    var maxFiles = 4;
    var maxSize = 5 * 1024 * 1024; // 5MB

    var existingCount = $previewContainer.find('.image-preview-item').length;
    var availableSlots = maxFiles - existingCount;

    console.log('现有图片:', existingCount, '可用位置:', availableSlots);

    if (files.length > availableSlots) {
        alert('最多只能上传' + maxFiles + '张图片，已选择' + existingCount + '张');
        return;
    }

    for (var i = 0; i < Math.min(files.length, availableSlots); i++) {
        var file = files[i];

        // 验证文件大小
        if (file.size > maxSize) {
            alert('文件 "' + file.name + '" 大小超过5MB限制');
            continue;
        }

        // 验证文件类型
        if (!file.type.startsWith('image/')) {
            alert('文件 "' + file.name + '" 不是图片格式');
            continue;
        }

        // 创建预览
        createImagePreview(file, $previewContainer);
    }
}

// 创建图片预览
function createImagePreview(file, $previewContainer) {
    var reader = new FileReader();
    var previewId = 'preview-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);

    reader.onload = function(e) {
        var previewHtml = `
            <div class="col-6 col-md-4 col-lg-3 image-preview-item" id="${previewId}">
                <div class="card h-100">
                    <div class="card-body p-2 text-center position-relative">
                        <img src="${e.target.result}"
                             class="img-fluid rounded"
                             style="height: 100px; object-fit: cover; width: 100%;"
                             alt="预览图片">
                        <button type="button"
                                class="btn btn-sm btn-danger btn-remove-preview"
                                data-preview-id="${previewId}">
                            <i class="bi bi-x"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
        $previewContainer.append(previewHtml);
        console.log('创建预览:', previewId);
    };

    reader.readAsDataURL(file);
}

// 图片动画功能
(function() {
    let currentImageModal = null;
    let currentImageElement = null;

    // 打开图片模态框
    window.openImageModal = function(imageUrl, thumbnailUrl, imageElement) {
        const modal = $('#imageModal');
        const $modalImage = $('#modalImage');

        // 保存当前图片元素
        currentImageElement = imageElement;

        // 先显示缩略图
        $modalImage.attr('src', thumbnailUrl);

        // 显示模态框
        modal.addClass('active');

        // 加载完整图片
        const fullImage = new Image();
        fullImage.onload = function() {
            $modalImage.attr('src', imageUrl);
        };
        fullImage.src = imageUrl;

        // 阻止背景滚动
        $('body').css('overflow', 'hidden');

        currentImageModal = modal;
    };

    // 关闭图片模态框
    window.closeImageModal = function() {
        if (currentImageModal) {
            currentImageModal.removeClass('active');
            $('body').css('overflow', '');

            // 延迟移除模态框以完成动画
            setTimeout(() => {
                $('#modalImage').attr('src', '');
            }, 300);
        }
    };

    // 点击图片打开模态框
    function initImageClickHandlers() {
        $(document).on('click', '.image-wrapper', function(e) {
            const $wrapper = $(this);
            const fullImageUrl = $wrapper.data('full-image');
            const thumbnailUrl = $wrapper.data('thumbnail');

            if (fullImageUrl) {
                openImageModal(fullImageUrl, thumbnailUrl, $wrapper.find('img')[0]);
            }
        });

        // 点击模态框背景关闭
        $(document).on('click', '.image-modal', function(e) {
            if (e.target === this) {
                closeImageModal();
            }
        });

        // 点击关闭按钮
        $(document).on('click', '.image-modal-close', function(e) {
            e.stopPropagation();
            closeImageModal();
        });

        // ESC键关闭
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && currentImageModal && currentImageModal.hasClass('active')) {
                closeImageModal();
            }
        });
    }

    // 初始化图片功能
    function initImageFeatures() {
        initImageClickHandlers();
        console.log('图片动画功能初始化完成');
    }

    // 页面加载完成后初始化
    $(document).ready(function() {
        initImageFeatures();
    });

    // 在刷新评论后重新初始化图片功能
    const originalRefreshComments = window.refreshComments;
    window.refreshComments = function() {
        originalRefreshComments();
        // 延迟初始化以确保DOM已更新
        setTimeout(initImageFeatures, 100);
    };
})();

// 修复点赞功能
(function() {
    let likeProcessing = new Set();

    function handleLikeClick(e) {
        e.preventDefault();
        e.stopImmediatePropagation();

        const $btn = $(this);
        const commentId = $btn.data('comment-id');

        // 防止重复点击
        if (likeProcessing.has(commentId)) {
            console.log('点赞操作正在进行中，忽略点击');
            return false;
        }

        likeProcessing.add(commentId);

        // 保存当前状态用于回退
        const currentState = {
            isLiked: $btn.hasClass('btn-danger'),
            currentCount: parseInt($btn.find('.likes-count').text()) || 0
        };

        // 立即更新UI（乐观更新）
        const expectedCount = currentState.isLiked ?
            Math.max(0, currentState.currentCount - 1) :
            currentState.currentCount + 1;
        const expectedLiked = !currentState.isLiked;

        updateLikeUI($btn, expectedCount, expectedLiked);
        $btn.prop('disabled', true).addClass('processing');

        // 发送请求
        $.ajax({
            url: `/activities/comment/${commentId}/like/`,
            type: 'POST',
            data: {
                csrfmiddlewaretoken: '{{ csrf_token }}'
            },
            timeout: 10000,
            success: function(response) {
                console.log('点赞响应:', response);

                if (response.success) {
                    // 使用后端返回的准确状态
                    updateLikeUI($btn, response.likes_count, response.action === 'liked');
                    console.log('点赞成功，更新UI');
                } else {
                    // 请求失败，恢复原始状态
                    updateLikeUI($btn, currentState.currentCount, currentState.isLiked);
                    showToast(response.message || '操作失败', 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('点赞请求失败:', error);
                // 恢复原始状态
                updateLikeUI($btn, currentState.currentCount, currentState.isLiked);
                showToast('网络错误，请重试', 'error');
            },
            complete: function() {
                $btn.prop('disabled', false).removeClass('processing');
                likeProcessing.delete(commentId);
            }
        });

        return false;
    }

    function updateLikeUI($btn, count, isLiked) {
        const $icon = $btn.find('i');
        const $count = $btn.find('.likes-count');

        // 确保计数不为负
        const safeCount = Math.max(0, count);
        $count.text(safeCount);

        if (isLiked) {
            $icon.removeClass('bi-heart').addClass('bi-heart-fill');
            $btn.removeClass('btn-outline-danger').addClass('btn-danger');
        } else {
            $icon.removeClass('bi-heart-fill').addClass('bi-heart');
            $btn.removeClass('btn-danger').addClass('btn-outline-danger');
        }
    }

    // 绑定点赞事件
    function bindLikeEvents() {
        console.log('绑定点赞事件...');

        // 先解绑所有事件防止重复绑定
        $(document).off('click', '.btn-like-comment');

        // 使用事件委托绑定
        $(document).on('click', '.btn-like-comment', handleLikeClick);
    }

    // 初始化
    $(document).ready(function() {
        bindLikeEvents();
        console.log('点赞功能初始化完成');
    });

    // 暴露给全局，供刷新后重新绑定
    window.bindLikeEvents = bindLikeEvents;

})();

// 更新评论提交处理
function updateCommentSubmitHandler() {
    // 保存原始处理函数
    var originalCommentSubmit = commentSubmitHandler;

    // 重写评论提交处理
    commentSubmitHandler = function(e) {
        e.preventDefault();

        if (commentState.isSubmitting) {
            console.log('评论提交被阻止：重复提交');
            return;
        }
        commentState.isSubmitting = true;

        var $form = $(this);
        var activityId = $form.data('activity-id');
        var content = $form.find('textarea[name="content"]').val().trim();
        var $submitBtn = $form.find('button[type="submit"]');
        var originalText = $submitBtn.html();

        // 验证：内容和图片不能同时为空
        var imageFiles = $form.find('.comment-image-input')[0].files;
        if (!content && imageFiles.length === 0) {
            showToast('评论内容或图片不能为空', 'error');
            commentState.isSubmitting = false;
            return;
        }

        console.log('提交评论，内容长度:', content.length, '图片数量:', imageFiles.length);

        // 显示加载状态
        $submitBtn.prop('disabled', true).html('<i class="bi bi-hourglass-split"></i> 发表中...');

        // 使用FormData支持文件上传
        var formData = new FormData();
        formData.append('content', content);
        formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');

        // 添加父评论ID（如果是回复）
        var parentId = $form.data('comment-id');
        if (parentId) {
            formData.append('parent_id', parentId);
        }

        // 添加图片文件
        for (var i = 0; i < imageFiles.length; i++) {
            formData.append('images', imageFiles[i]);
        }

        $.ajax({
            url: '/activities/' + activityId + '/comment/',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                commentState.isSubmitting = false;
                $submitBtn.prop('disabled', false).html(originalText);
                console.log('评论提交响应:', response);

                if (response.success) {
                    // 清空表单和预览
                    $form.find('textarea').val('');
                    clearImagePreviews('main');

                    // 隐藏回复表单（如果是回复）
                    if (parentId) {
                        $form.closest('.reply-form').hide();
                    }

                    showToast('评论发表成功！', 'success');

                    // 延迟刷新评论列表
                    setTimeout(function() {
                        refreshComments();
                    }, 500);
                } else {
                    showToast(response.message, 'error');
                }
            },
            error: function(xhr, status, error) {
                commentState.isSubmitting = false;
                $submitBtn.prop('disabled', false).html(originalText);
                console.error('评论提交错误:', error);
                showToast('发表评论失败，请重试', 'error');
            }
        });
    };
}

// 关注/取消关注功能
$(document).on('click', '.btn-follow-user', function() {
    var userId = $(this).data('user-id');
    var $btn = $(this);
    var isFollowing = $btn.hasClass('btn-secondary');
    var url = isFollowing ? '/social/unfollow/' + userId + '/' : '/social/follow/' + userId + '/';

    $.ajax({
        url: url,
        type: 'POST',
        data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
        success: function(response) {
            if (response.success) {
                if (response.action === 'followed') {
                    $btn.html('<i class="bi bi-check"></i> 已关注').removeClass('btn-outline-secondary').addClass('btn-secondary');
                    showToast('关注成功', 'success');
                } else {
                    $btn.html('<i class="bi bi-plus"></i> 关注').removeClass('btn-secondary').addClass('btn-outline-secondary');
                    showToast('已取消关注', 'info');
                }
            } else {
                showToast(response.message, 'error');
            }
        },
        error: function() {
            showToast('操作失败，请重试', 'error');
        }
    });
});

// 更新签到按钮状态的函数
function updateCheckinButton(activityId) {
    var $checkinBtn = $('.btn-checkin[data-activity-id="' + activityId + '"]');
    if ($checkinBtn.length) {
        $checkinBtn.prop('disabled', true)
                   .html('<i class="bi bi-check-circle"></i> 已签到')
                   .removeClass('btn-checkin');
    }
}

// 评论提交处理函数
var commentSubmitHandler = function(e) {
    e.preventDefault();

    // 防止重复提交
    if (commentState.isSubmitting) {
        console.log('评论提交被阻止：重复提交');
        return;
    }
    commentState.isSubmitting = true;

    var $form = $(this);
    var activityId = $form.data('activity-id');
    var content = $form.find('textarea[name="content"]').val().trim();
    var $submitBtn = $form.find('button[type="submit"]');
    var originalText = $submitBtn.html();

    console.log('评论提交开始:', content);

    // 前端验证评论内容
    if (!content) {
        showToast('评论内容不能为空', 'error');
        commentState.isSubmitting = false;
        return;
    }

    if (content.length < 2) {
        showToast('评论内容至少需要2个字符', 'error');
        commentState.isSubmitting = false;
        return;
    }

    if (content.length > 1000) {
        showToast('评论内容不能超过1000个字符', 'error');
        commentState.isSubmitting = false;
        return;
    }

    // 显示加载状态
    $submitBtn.prop('disabled', true).html('<i class="bi bi-hourglass-split"></i> 发表中...');

    $.ajax({
        url: '/activities/' + activityId + '/comment/',
        type: 'POST',
        data: {
            content: content,
            csrfmiddlewaretoken: '{{ csrf_token }}'
        },
        success: function(response) {
            commentState.isSubmitting = false;
            $submitBtn.prop('disabled', false).html(originalText);
            console.log('评论提交响应:', response);

            if (response.success) {
                // 清空输入框
                $form.find('textarea').val('');
                showToast('评论发表成功！', 'success');

                // 延迟刷新评论列表
                setTimeout(function() {
                    refreshComments();
                }, 500);
            } else {
                showToast(response.message, 'error');
            }
        },
        error: function(xhr, status, error) {
            commentState.isSubmitting = false;
            $submitBtn.prop('disabled', false).html(originalText);
            console.error('评论提交错误:', error);
            showToast('发表评论失败，请重试', 'error');
        }
    });
};

// 回复提交处理函数
var replySubmitHandler = function(e) {
    e.preventDefault();

    var $form = $(this);
    var parentCommentId = $form.data('comment-id');
    var content = $form.find('textarea[name="content"]').val().trim();
    var activityId = $('#comment-form').data('activity-id');

    // 防止重复提交
    if ($form.hasClass('processing')) return;
    $form.addClass('processing');

    // 验证回复内容
    if (!content) {
        showToast('回复内容不能为空', 'error');
        $form.removeClass('processing');
        return;
    }

    var $submitBtn = $form.find('button[type="submit"]');
    var originalText = $submitBtn.html();

    // 显示加载状态
    $submitBtn.prop('disabled', true).html('<i class="bi bi-hourglass-split"></i> 回复中...');

    $.ajax({
        url: '/activities/' + activityId + '/comment/',
        type: 'POST',
        data: {
            content: content,
            parent_id: parentCommentId,
            csrfmiddlewaretoken: '{{ csrf_token }}'
        },
        success: function(response) {
            $form.removeClass('processing');
            $submitBtn.prop('disabled', false).html(originalText);

            if (response.success) {
                // 清空回复框并隐藏
                $form.find('textarea').val('');
                $form.closest('.reply-form').hide();
                showToast('回复成功！', 'success');

                // 延迟刷新评论列表
                setTimeout(function() {
                    refreshComments();
                }, 500);
            } else {
                showToast(response.message, 'error');
            }
        },
        error: function() {
            $form.removeClass('processing');
            $submitBtn.prop('disabled', false).html(originalText);
            showToast('回复失败，请重试', 'error');
        }
    });
};

// 删除评论功能
function initDeleteHandlers() {
    console.log('初始化删除事件处理器...');

    // 先解绑所有可能重复绑定的事件
    $(document).off('click', '.btn-delete-comment');

    // 使用事件委托绑定删除按钮
    $(document).on('click', '.btn-delete-comment', function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log('删除按钮被点击');

        var commentId = $(this).data('comment-id');
        var $btn = $(this);

        console.log('要删除的评论ID:', commentId);

        if (!confirm('确定要删除这条评论吗？删除后所有回复也会被删除。')) {
            return false;
        }

        // 添加加载状态
        var originalHtml = $btn.html();
        $btn.prop('disabled', true).html('<i class="bi bi-hourglass-split"></i>');

        $.ajax({
            url: '/activities/comment/' + commentId + '/delete/',
            type: 'POST',
            data: {
                csrfmiddlewaretoken: '{{ csrf_token }}'
            },
            success: function(response) {
                console.log('删除响应:', response);
                $btn.prop('disabled', false).html(originalHtml);

                if (response.success) {
                    // 找到评论元素并移除
                    var $commentElement = $('[data-comment-id="' + commentId + '"]');
                    if ($commentElement.length) {
                        $commentElement.fadeOut(300, function() {
                            $(this).remove();

                            // 检查是否还有评论
                            if ($('.comment-item').length === 0) {
                                $('.comments-list').html('<p class="text-muted text-center py-4">暂无评论，快来抢沙发吧！</p>');
                            }
                        });
                    } else {
                        // 如果找不到元素，刷新整个评论列表
                        refreshComments();
                    }
                    showToast('评论已删除', 'success');
                } else {
                    showToast('删除失败: ' + response.message, 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('删除请求错误:', error);
                $btn.prop('disabled', false).html(originalHtml);
                showToast('删除失败，请重试', 'error');
            }
        });

        return false;
    });

    console.log('删除事件处理器初始化完成');
}

// 移除图片删除功能（不再需要单独的图片删除）

// 回复功能
function initReplyHandlers() {
    console.log('初始化回复事件处理器...');

    // 解绑所有可能重复绑定的事件
    $(document).off('click', '.btn-reply-comment');
    $(document).off('click', '.btn-cancel-reply');
    $(document).off('submit', '.reply-comment-form');

    // 回复按钮点击事件
    $(document).on('click', '.btn-reply-comment', function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log('回复按钮被点击');

        var commentId = $(this).data('comment-id');
        var username = $(this).data('username');
        var $replyForm = $('#reply-form-' + commentId);

        console.log('回复评论ID:', commentId, '用户名:', username);

        if ($replyForm.length === 0) {
            console.error('找不到回复表单: #reply-form-' + commentId);
            return false;
        }

        // 隐藏其他回复表单
        $('.reply-form').hide();

        // 显示当前回复表单
        $replyForm.show();

        // 设置placeholder并聚焦
        var $textarea = $replyForm.find('textarea');
        $textarea.attr('placeholder', '回复 @' + username + '...');
        $textarea.focus();

        return false;
    });

    // 取消回复事件
    $(document).on('click', '.btn-cancel-reply', function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log('取消回复按钮被点击');

        $(this).closest('.reply-form').hide();
        return false;
    });

    // 回复表单提交事件
    $(document).on('submit', '.reply-comment-form', function(e) {
        e.preventDefault();
        console.log('回复表单提交');

        var $form = $(this);
        var parentCommentId = $form.data('comment-id');
        var content = $form.find('textarea[name="content"]').val().trim();
        var activityId = $('#comment-form').data('activity-id');

        console.log('回复内容:', content, '父评论ID:', parentCommentId);

        // 防止重复提交
        if ($form.hasClass('processing')) {
            console.log('表单正在处理中，跳过重复提交');
            return false;
        }
        $form.addClass('processing');

        // 验证回复内容
        if (!content) {
            showToast('回复内容不能为空', 'error');
            $form.removeClass('processing');
            return false;
        }

        if (content.length < 2) {
            showToast('回复内容至少需要2个字符', 'error');
            $form.removeClass('processing');
            return false;
        }

        if (content.length > 1000) {
            showToast('回复内容不能超过1000个字符', 'error');
            $form.removeClass('processing');
            return false;
        }

        var $submitBtn = $form.find('button[type="submit"]');
        var originalText = $submitBtn.html();

        // 显示加载状态
        $submitBtn.prop('disabled', true).html('<i class="bi bi-hourglass-split"></i> 回复中...');

        $.ajax({
            url: '/activities/' + activityId + '/comment/',
            type: 'POST',
            data: {
                content: content,
                parent_id: parentCommentId,
                csrfmiddlewaretoken: '{{ csrf_token }}'
            },
            success: function(response) {
                console.log('回复提交响应:', response);
                $form.removeClass('processing');
                $submitBtn.prop('disabled', false).html(originalText);

                if (response.success) {
                    // 清空回复框并隐藏
                    $form.find('textarea').val('');
                    $form.closest('.reply-form').hide();

                    // 延迟刷新评论列表
                    setTimeout(function() {
                        refreshComments();
                    }, 500);
                } else {
                    showToast('回复失败: ' + response.message, 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('回复提交错误:', error);
                $form.removeClass('processing');
                $submitBtn.prop('disabled', false).html(originalText);
                showToast('回复失败，请重试', 'error');
            }
        });

        return false;
    });

    console.log('回复事件处理器初始化完成');
}

// 刷新评论列表
function refreshComments() {
    if (commentRefresh.isRefreshing || commentState.isSubmitting) {
        console.log('刷新被阻止: 正在刷新或提交中');
        return;
    }

    commentRefresh.isRefreshing = true;
    var activityId = $('#comment-form').data('activity-id');

    console.log('开始刷新评论列表...');

    $.ajax({
        url: '/activities/' + activityId + '/?partial=comments',
        type: 'GET',
        success: function(response) {
            $('.comments-list').html(response);
            console.log('评论列表刷新完成');

            // 重新绑定所有事件
            setTimeout(function() {
                bindLikeEvents();
                initReplyHandlers();
                initDeleteHandlers();
            }, 100);
        },
        error: function(xhr, status, error) {
            console.error('刷新评论列表失败:', error);
        },
        complete: function() {
            commentRefresh.isRefreshing = false;
            console.log('刷新评论列表完成');
        }
    });
}

// 启动自动刷新
function startCommentAutoRefresh() {
    if (commentRefresh.intervalId) {
        clearInterval(commentRefresh.intervalId);
    }

    // 每30秒自动刷新一次评论列表
    commentRefresh.intervalId = setInterval(function() {
        if (!commentRefresh.isRefreshing && !commentState.isSubmitting) {
            refreshComments();
        }
    }, 30000);
}

// 停止自动刷新
function stopCommentAutoRefresh() {
    if (commentRefresh.intervalId) {
        clearInterval(commentRefresh.intervalId);
        commentRefresh.intervalId = null;
    }
}

// 手动刷新
$(document).on('click', '#manual-refresh-comments', function() {
    var $btn = $(this);
    $btn.prop('disabled', true).html('<i class="bi bi-arrow-clockwise"></i> 刷新中...');

    refreshComments();

    setTimeout(function() {
        $btn.prop('disabled', false).html('<i class="bi bi-arrow-clockwise"></i> 刷新');
    }, 1000);
});

// 初始化所有事件处理器
function initEventHandlers() {
    console.log('初始化所有事件处理器...');

    // 评论表单提交
    $('#comment-form').off('submit').on('submit', commentSubmitHandler);

    // 初始化特定功能的事件
    initReplyHandlers();
    initDeleteHandlers();
    bindLikeEvents();

    console.log('所有事件处理器初始化完成');
}

// 文档加载完成
$(document).ready(function() {
    console.log('=== 文档加载完成，开始初始化 ===');

    // 初始化图片上传功能
    initImageUpload();

    // 更新评论提交处理以支持图片
    updateCommentSubmitHandler();

    // 初始化所有事件处理器
    initEventHandlers();

    // 启动自动刷新
    startCommentAutoRefresh();

    console.log('=== 初始化完成 ===');

    // 取消报名功能
    $(document).on('click', '.btn-unregister-activity', function() {
        var activityId = $(this).data('activity-id');
        var $btn = $(this);

        if ($btn.hasClass('processing')) return;
        $btn.addClass('processing');

        if (confirm('确定要取消报名吗？')) {
            $.ajax({
                url: '/activities/' + activityId + '/unregister/',
                type: 'POST',
                data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
                success: function(response) {
                    $btn.removeClass('processing');
                    if (response.success) {
                        updateRegistrationButtons(false, activityId);
                        showToast('已取消报名', 'info');
                    } else {
                        showToast(response.message, 'error');
                    }
                },
                error: function() {
                    $btn.removeClass('processing');
                    showToast('取消报名失败，请重试', 'error');
                }
            });
        } else {
            $btn.removeClass('processing');
        }
    });

    // 报名功能
    $(document).on('click', '.btn-register-activity', function() {
        var activityId = $(this).data('activity-id');
        var $btn = $(this);

        if ($btn.hasClass('processing')) return;
        $btn.addClass('processing');

        $.ajax({
            url: '/activities/' + activityId + '/register/',
            type: 'POST',
            data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
            success: function(response) {
                $btn.removeClass('processing');
                if (response.success) {
                    updateRegistrationButtons(true, activityId, false);
                    showToast('报名成功！', 'success');
                } else {
                    showToast(response.message, 'error');
                }
            },
            error: function() {
                $btn.removeClass('processing');
                showToast('报名失败，请重试', 'error');
            }
        });
    });

    // 签到功能
    $(document).on('click', '.btn-checkin', function() {
        var activityId = $(this).data('activity-id');
        var $btn = $(this);

        if ($btn.hasClass('processing')) return;
        $btn.addClass('processing');

        $.ajax({
            url: '/activities/' + activityId + '/checkin/',
            type: 'POST',
            data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
            success: function(response) {
                $btn.removeClass('processing');
                if (response.success) {
                    showToast('签到成功！', 'success');
                    updateCheckinButton(activityId);
                } else {
                    showToast(response.message, 'error');
                }
            },
            error: function() {
                $btn.removeClass('processing');
                showToast('签到失败，请重试', 'error');
            }
        });
    });

    // 评分功能 - 添加报名验证
    $('.rating-star').click(function() {
        var $star = $(this);
        var score = $star.data('score');
        var activityId = $star.data('activity-id');

        // 防止重复点击
        if ($star.hasClass('processing')) return;
        $star.addClass('processing');

        $.ajax({
            url: '/activities/' + activityId + '/rate/',
            type: 'POST',
            data: {
                score: score,
                csrfmiddlewaretoken: '{{ csrf_token }}'
            },
            success: function(response) {
                $star.removeClass('processing');
                if (response.success) {
                    showToast('评分成功', 'success');
                    // 刷新页面以更新评分显示
                    setTimeout(function() {
                        location.reload();
                    }, 1000);
                } else {
                    showToast(response.message, 'error');
                    // 如果是未报名导致的错误，可以给出更明确的提示
                    if (response.message.includes('报名')) {
                        showToast('请先报名参加活动再进行评分', 'warning');
                    }
                }
            },
            error: function(xhr, status, error) {
                $star.removeClass('processing');
                showToast('评分失败，请重试', 'error');
            }
        });
    });
});

// 更新报名按钮状态的函数
function updateRegistrationButtons(isRegistered, activityId, isCheckedIn = false) {
    var buttonsContainer = $('.d-flex.gap-2.mb-4');

    if (isRegistered) {
        var checkinButton = isCheckedIn ?
            '<button class="btn btn-success" disabled><i class="bi bi-check-circle"></i> 已签到</button>' :
            '<button class="btn btn-success btn-checkin" data-activity-id="' + activityId + '"><i class="bi bi-check-circle"></i> 签到</button>';

        buttonsContainer.html(`
            <button class="btn btn-secondary btn-unregister-activity" data-activity-id="${activityId}">
                <i class="bi bi-x-circle"></i> 取消报名
            </button>
            ${checkinButton}
        `);
    } else {
        buttonsContainer.html(`
            <button class="btn btn-primary btn-register-activity" data-activity-id="${activityId}">
                <i class="bi bi-person-plus"></i> 报名参加
            </button>
        `);
    }

    updateParticipantsCount(isRegistered);
}

// 更新参与人数显示
function updateParticipantsCount(isRegistered) {
    var participantsText = $('p:contains("参与人数：")');
    var currentText = participantsText.text();
    var matches = currentText.match(/(\d+)\/(\d+)/);

    if (matches) {
        var current = parseInt(matches[1]);
        var max = parseInt(matches[2]);

        if (isRegistered) {
            current += 1;
        } else {
            current -= 1;
        }

        participantsText.html('<i class="bi bi-people"></i> <strong>参与人数：</strong>' + current + '/' + max);
    }
}
</script>
{% endblock %}